﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace Chromium_Updater
{
    public partial class CUpdatesForm : Form
    {
        #region Variables

        private static bool formOpen = false;
        //
        List<CULogEntry> logEntries;
        //
        private delegate void emptyD();
        private delegate void addCULogEntryToListViewD(CULogEntry entry);
        private delegate void reduceActionCountD(string action);
        
        public static bool isOpen
        {
            get { return formOpen; }
        }

        #endregion

        #region Form Load/Close

        public CUpdatesForm()
        {
            InitializeComponent();
        }

        private void CUpdatesForm_Load(object sender, EventArgs e)
        {
            formOpen = true;
            //
            new Thread(new ThreadStart(threadedLoad)).Start();
        }

        private void threadedLoad()
        {
            logEntries = CULReader.loadCULog();
            showAll();
        }

        private void CUpdatesForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            formOpen = false;
        }

        #endregion

        #region Show Functions (Show All)

        private void resetListView()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new emptyD(resetListView));
                return;
            }
            //
            listView1.Items.Clear();
            //
            label2.Text = CULReader.Checks.ToString();
            label5.Text = CULReader.Downloads.ToString();
            label6.Text = CULReader.Installs.ToString();
        }

        private void showAction(string action)
        {
            resetListView();
            new Thread(new ParameterizedThreadStart(showActionWorker)).Start(action);
        }

        private void showActionWorker(object action)
        {
            string _action = action.ToString();
            foreach (CULogEntry entry in logEntries)
            {
                if (_action.Contains(entry.Action))
                {
                    if (checkBox5.Checked)
                    {
                        if (!entry.Message.Contains("Error")) { addCULogEntryToListView(entry); }
                        else { reduceActionCount(entry.Action); }
                    }
                    else if (checkBox4.Checked)
                    {
                        if (entry.Message.Contains("Error")) { addCULogEntryToListView(entry); }
                        else { reduceActionCount(entry.Action); }
                    }
                    else { addCULogEntryToListView(entry); }
                }
                else { reduceActionCount(entry.Action); }
            }
        }

        private void showAll()
        {
            resetListView();
            new Thread(new ThreadStart(showAllWorker)).Start();
        }

        private void showAllWorker()
        {
            foreach (CULogEntry entry in logEntries)
            {
                if (checkBox5.Checked)
                {
                    if (!entry.Message.Contains("Error")) { addCULogEntryToListView(entry); }
                    else { reduceActionCount(entry.Action); }
                }
                else if (checkBox4.Checked)
                {
                    if (entry.Message.Contains("Error")) { addCULogEntryToListView(entry); }
                    else { reduceActionCount(entry.Action); }
                }
                else { addCULogEntryToListView(entry); }
            }
        }

        #endregion

        #region Delegated Functions

        private void clearListView()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new emptyD(clearListView));
                return;
            }
            //
            listView1.Items.Clear();
        }

        private void addCULogEntryToListView(CULogEntry entry)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new addCULogEntryToListViewD(addCULogEntryToListView), new object[] { entry });
                return;
            }
            //
            listView1.Items.Add(new ListViewItem(new string[] { entry.Time.ToString(), entry.Action, entry.Message }));
        }

        private void reduceActionCount(string action)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new reduceActionCountD(reduceActionCount), new object[] { action });
                return;
            }
            //
            switch (action)
            {
                case "Check":
                    label2.Text = (Convert.ToInt32(label2.Text) - 1).ToString();
                    break;
                case "Download":
                    label5.Text = (Convert.ToInt32(label5.Text) - 1).ToString();
                    break;
                case "Install":
                    label6.Text = (Convert.ToInt32(label6.Text) - 1).ToString();
                    break;
            }
        }

        #endregion

        #region Checkboxes

        #region Action Checkboxes

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                checkBox2.Enabled = false;
                checkBox3.Enabled = false;
                //
                showAction("Check");
            }
            else
            {
                checkBox2.Enabled = true;
                checkBox3.Enabled = true;
                //
                showAll();
            }
        }

        private void checkBox2_Click(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                checkBox1.Enabled = false;
                checkBox3.Enabled = false;
                //
                showAction("PreDownload;Download");
            }
            else
            {
                showAll();
                //
                checkBox1.Enabled = true;
                checkBox3.Enabled = true;
            }
        }

        private void checkBox3_Click(object sender, EventArgs e)
        {
            if (checkBox3.Checked)
            {
                checkBox1.Enabled = false;
                checkBox2.Enabled = false;
                //
                showAction("Install");
            }
            else
            {
                showAll();
                //
                checkBox1.Enabled = true;
                checkBox2.Enabled = true;
            }
        }

        #endregion

        #region Success/Error

        private void checkBox5_Click(object sender, EventArgs e)
        {
            if (checkBox5.Checked)
            {
                checkBox4.Enabled = false;
                //
                string _action = getCurrentShownAction();
                if (String.IsNullOrEmpty(_action)) { showAll(); }
                else { showAction(_action); }
            }
            else
            {
                string _action = getCurrentShownAction();
                if (String.IsNullOrEmpty(_action)) { showAll(); }
                else { showAction(_action); }
                //
                checkBox4.Enabled = true;
            }
        }

        private string getCurrentShownAction()
        {
            if (checkBox1.Checked)
            {
                return "Check";
            }
            else if (checkBox2.Checked)
            {
                return "PreDownload;Download";
            }
            else if (checkBox3.Checked)
            {
                return "Install";
            }
            else
            {
                return "";
            }
        }

        private void checkBox4_Click(object sender, EventArgs e)
        {
            if (checkBox4.Checked)
            {
                checkBox5.Enabled = false;
                //
                string _action = getCurrentShownAction();
                if (String.IsNullOrEmpty(_action)) { showAll(); }
                else { showAction(_action); }
            }
            else
            {
                string _action = getCurrentShownAction();
                if (String.IsNullOrEmpty(_action)) { showAll(); }
                else { showAction(_action); }
                //
                checkBox5.Enabled = true;
            }
        }

        #endregion

        #endregion

        #region Buttons

        private void button1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                string outputToClip = "";
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    outputToClip += item.SubItems[0].Text + " - " + item.SubItems[1].Text + ": " + item.SubItems[2].Text + "\r\n";
                }
                outputToClip = outputToClip.Substring(0, outputToClip.Length - 4);
                Clipboard.Clear();
                Clipboard.SetText(outputToClip);
                MessageBox.Show("Saved selected entries to clipboard.");
            }
            else
            {
                string outputToClip = "";
                foreach (CULogEntry entry in logEntries)
                {
                    outputToClip += CULReader.CULogEntryToString(entry) + "\r\n";
                }
                outputToClip = outputToClip.Substring(0, outputToClip.Length - 4);
                Clipboard.Clear();
                Clipboard.SetText(outputToClip);
                MessageBox.Show("Saved current list to clipboard.");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to clear the log?", "Chromium Updater", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                CULogger.clearLog();
            }
        }

        #endregion
    }
}
